<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus';
import { dailyLogAPI } from '@/api/index'

axios.interceptors.request.use(config => {
  const token = localStorage.getItem('access');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});

type TObj = Record<string, any>;

const formatDate = (d: any) => d ? moment(d).format('YYYY-MM-DD') : '';
const smoking_results_list: TObj = {
    1: '一次通过',
    2: '二次通过',
    3: '二次以上',
}
const if_extension_list: TObj = {
    1: '是',
    0: '否',
}
const initQuery = {
    demand_id: null,
    name: null,
    version: null,
    tester: null,
    test_date: null,
    launch_time: null,
    status: null,
};
const { value: state } = ref({
    loading: false,
    tableData: [] as TObj[],
    total: 0,
    pageSize: 20,
    currentPage: 1,
    queryData: { ...initQuery },
    statistics: { demand_time_total: 0, test_time_total: 0 },
});

const dialogVisible = ref(false);
const dialogLoading = ref(false);
const isEdit = ref(false);
const form = reactive({
  id: null,
  name: '',
  tester: '',
  demand_time: '',
  version: '',
  module: '',
  product: '',
  review_time: '',
  status: '',
  test_time: '',
  test_date: '',
  launch_time: '',
});

const fetchData = async (page = state.currentPage, size = state.pageSize) => {
    state.loading = true;
    try {
        const params: TObj = {
            page,
            size,
            ...state.queryData,
            ...(Array.isArray(state.queryData.test_date) && state.queryData.test_date[0] && state.queryData.test_date[1]
                ? {
                    test_date_start: formatDate(state.queryData.test_date[0]),
                    test_date_end: formatDate(state.queryData.test_date[1]),
                }
                : {}),
            ...(Array.isArray(state.queryData.launch_time) && state.queryData.launch_time[0] && state.queryData.launch_time[1]
                ? {
                    launch_time_start: formatDate(state.queryData.launch_time[0]),
                    launch_time_end: formatDate(state.queryData.launch_time[1]),
                }
                : {}),
        };
        delete params.test_date;
        delete params.launch_time;
        const response = await dailyLogAPI.getList(params) || {};
        state.tableData = response.results ?? [];
        state.total = response.count ?? 0;
        state.statistics.demand_time_total = response.demand_time_total ?? 0;
        state.statistics.test_time_total = response.test_time_total ?? 0;
    } catch (error) {
        ElMessage.error('获取日志失败');
        console.error('Error fetching logs:', error);
    }
    state.loading = false;
};

const handleSizeChange = (val: number) => {
    state.pageSize = val;
    fetchData(state.currentPage, val);
};
const handleCurrentChange = (val: number) => {
    state.currentPage = val;
    fetchData(val, state.pageSize);
};
const handleSearch = () => {
    fetchData();
};

const handleReset = () => {
  state.queryData = { ...initQuery };
  fetchData();
};

const handleAdd = () => {
  isEdit.value = false;
  Object.assign(form, {
    id: null,
    name: '',
    tester: '',
    demand_time: '',
    version: '',
    module: '',
    product: '',
    review_time: '',
    status: '',
    test_time: '',
    test_date: '',
    launch_time: '',
  });
  dialogVisible.value = true;
};

const handleEdit = (row: TObj) => {
  isEdit.value = true;
  Object.assign(form, row);
  dialogVisible.value = true;
};

const handleDialogConfirm = async () => {
  dialogLoading.value = true;
  try {
    if (isEdit.value) {
      await dailyLogAPI.update(form.id, form);
      ElMessage.success('编辑成功');
    } else {
      await dailyLogAPI.create(form);
      ElMessage.success('新增成功');
    }
    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    ElMessage.error(isEdit.value ? '编辑失败' : '新增失败');
  }
  dialogLoading.value = false;
};

const handleDelete = async (row: TObj) => {
  try {
    await ElMessageBox.confirm('确定要删除这条需求吗？', '提示', { type: 'warning' });
    await dailyLogAPI.delete(row.id);
    ElMessage.success('删除成功');
    fetchData();
  } catch (error) {
    // 用户取消或请求失败
  }
};

onMounted(() => {
    fetchData();
});
</script>

<template>
  <div class="log-wrap">
    <div class="log-search">
      <el-input v-model="state.queryData.demand_id" placeholder="请输入ID" class="width200" />
      <el-input v-model="state.queryData.name" placeholder="请输入需求标题" class="width200" />
      <el-input v-model="state.queryData.version" placeholder="请输入项目" class="width200" />
      <el-input v-model="state.queryData.tester" placeholder="请输入测试人员" class="width200" />
      <el-input v-model="state.queryData.status" placeholder="请输入需求状态" class="width200" />
      <div class="date-wrap">
        <el-date-picker v-model="state.queryData.test_date" type="daterange" range-separator="-"
          start-placeholder="提测日期开始" end-placeholder="提测日期结束" />
      </div>
      <div class="date-wrap">
        <el-date-picker v-model="state.queryData.launch_time" type="daterange" range-separator="-"
          start-placeholder="上线日期开始" end-placeholder="上线日期结束" />
      </div>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button type="success" @click="handleAdd">新增需求</el-button>
    </div>
    <div class="sta-wrap">
      统计：
      <span class="m-r-10">需求规模:{{ state.statistics.demand_time_total }}</span>
      <span>测试工时:{{ state.statistics.test_time_total }}</span>
    </div>
    <el-table :data="state.tableData" border style="width: 100%;" v-loading="state.loading"
      :header-cell-style="{ color: '#000', backgroundColor: '#61c5fc', height: '81px' }"
      :row-style="{ backgroundColor: '#cce4fa' }">
      <el-table-column label="操作" width="160" fixed="left">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="demand_id" label="ID" width="70" fixed="left" />
      <el-table-column prop="name" label="需求标题" width="400" fixed="left" show-overflow-tooltip="true" />
      <el-table-column prop="tester" label="测试人员" width="100" show-overflow-tooltip="true" fixed="left" />
      <el-table-column prop="demand_time" label="需求规模" width="90" />
      <el-table-column prop="version" label="项目" width="330" show-overflow-tooltip="true" />
      <el-table-column prop="module" label="模块" width="110" />
      <el-table-column prop="product" label="产品经理" width="100" />
      <el-table-column prop="review_time" label="评审时间" width="100">
        <template v-slot="scope">
          <span>{{ scope.row.review_time ? (scope.row.review_time.length > 10 ? scope.row.review_time.slice(0, 10) : scope.row.review_time) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="需求状态" width="100" />
      <el-table-column prop="test_time" label="测试工时" width="100" />
      <el-table-column prop="test_date" label="提测日期" width="100" />
      <el-table-column prop="launch_time" label="上线日期" width="100" />
      <el-table-column prop="smoking_results" label="冒烟结果" width="100">
        <template v-slot="scope">
          <span>{{ smoking_results_list?.[scope.row.smoking_results] || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="if_extension" label="提测是否延期" width="110">
        <template v-slot="scope">
          <span>{{ if_extension_list[scope.row.if_extension] || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="test_schedule" label="测试进度" width="100">
        <template v-slot="scope">
          <span>{{ scope.row.test_schedule ? scope.row.test_schedule + '%' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="function_case_num" label="功能用例数" width="100" />
      <el-table-column prop="automation_case_num" label="自动化用例数" width="112" />
      <el-table-column prop="key_words" label="关键字" width="399" show-overflow-tooltip="true" />
      <el-table-column prop="log_content" label="日志内容" min-width="300" show-overflow-tooltip="true" />
    </el-table>
    <div class="example-pagination-block">
      <span class="m-r-5 font-12">共 {{ state.total }}</span>
      <el-pagination v-model:currentPage="state.currentPage" v-model:page-size="state.pageSize"
        :page-sizes="[20, 50, 100, 200]" :small="true" :disabled="false" :background="false"
        layout="sizes, prev, pager, next" :total="state.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑需求' : '新增需求'" width="50%" :before-close="() => dialogVisible = false">
      <el-form :model="form" label-width="100px" v-loading="dialogLoading">
        <el-form-item label="需求标题">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="测试人员">
          <el-input v-model="form.tester" />
        </el-form-item>
        <el-form-item label="需求规模">
          <el-input v-model="form.demand_time" />
        </el-form-item>
        <el-form-item label="项目">
          <el-input v-model="form.version" />
        </el-form-item>
        <el-form-item label="模块">
          <el-input v-model="form.module" />
        </el-form-item>
        <el-form-item label="产品经理">
          <el-input v-model="form.product" />
        </el-form-item>
        <el-form-item label="评审时间">
          <el-date-picker v-model="form.review_time" type="date" placeholder="请选择" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="需求状态">
          <el-input v-model="form.status" />
        </el-form-item>
        <el-form-item label="测试工时">
          <el-input v-model="form.test_time" />
        </el-form-item>
        <el-form-item label="提测日期">
          <el-date-picker v-model="form.test_date" type="date" placeholder="请选择" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="上线日期">
          <el-date-picker v-model="form.launch_time" type="date" placeholder="请选择" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDialogConfirm" :loading="dialogLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.log-wrap {
  padding: 20px;
}
.log-search {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 16px;
  align-items: center;
}
.sta-wrap {
  display: flex;
  height: 20px;
  align-items: center;
  color: blue;
  font-size: 14px;
}
.example-pagination-block {
  display: flex;
  height: 40px;
  align-items: center;
  justify-content: end;
  margin-top: 10px;
}
.width200 {
  width: 200px;
}
.date-wrap {
  margin-right: 10px;
}
</style> 